package org.dromara.system.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.dromara.common.core.constant.SystemConstants;
import org.dromara.common.core.exception.ServiceException;
import org.dromara.common.core.utils.MapstructUtils;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.mybatis.core.page.PageQuery;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.system.domain.SysDept;
import org.dromara.system.domain.TalentDeclarationInfo;
import org.dromara.system.domain.TalentUser;
import org.dromara.system.domain.bo.TalentDeclarationInfoBo;
import org.dromara.system.domain.vo.SysDeptVo;
import org.dromara.system.domain.vo.TalentDeclarationInfoVo;
import org.dromara.system.mapper.SysDeptMapper;
import org.dromara.system.mapper.TalentDeclarationInfoMapper;
import org.dromara.system.mapper.TalentUserMapper;
import org.dromara.system.service.ITalentDeclarationInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Collection;
import java.util.Date;
import java.util.List;

import static cn.hutool.core.date.DateTime.now;

/**
 * 人才申报信息Service业务层处理
 *
 * @author 毛宁川
 * date 2025-09-05
 */
@Slf4j
@Service
public class TalentDeclarationInfoServiceImpl implements ITalentDeclarationInfoService {


    @Autowired
    private TalentDeclarationInfoMapper talentDeclarationInfoMapper;

    @Autowired
    private TalentUserMapper talentUserMapper;

    @Autowired
    private SysDeptMapper sysDeptMapper;

    /**
     * 查询人才申报信息
     *
     * @param infoId 主键
     * @return 人才申报信息
     */
    @Override
    public TalentDeclarationInfoVo queryById(Long infoId) {
        return talentDeclarationInfoMapper.selectVoById(infoId);
    }

    /**
     * 分页查询人才申报信息列表
     *
     * @param bo        查询条件
     * @param pageQuery 分页参数
     * @return 人才申报信息分页列表
     */
    @Override
    public TableDataInfo<TalentDeclarationInfoVo> queryPageList(TalentDeclarationInfoBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<TalentDeclarationInfo> lqw = buildQueryWrapper(bo);
        Page<TalentDeclarationInfoVo> result = talentDeclarationInfoMapper.selectPageDeclarationInfoList(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询符合条件的人才申报信息列表
     *
     * @param bo 查询条件
     * @return 人才申报信息列表
     */
    @Override
    public List<TalentDeclarationInfoVo> queryList(TalentDeclarationInfoBo bo) {
        LambdaQueryWrapper<TalentDeclarationInfo> lqw = buildQueryWrapper(bo);
        return talentDeclarationInfoMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<TalentDeclarationInfo> buildQueryWrapper(TalentDeclarationInfoBo bo) {
        LambdaQueryWrapper<TalentDeclarationInfo> lqw = Wrappers.lambdaQuery();
        lqw.orderByAsc(TalentDeclarationInfo::getInfoId);
        lqw.eq(bo.getXcxUserId() != null, TalentDeclarationInfo::getXcxUserId, bo.getXcxUserId());
        lqw.like(StringUtils.isNotBlank(bo.getUserName()), TalentDeclarationInfo::getUserName, bo.getUserName());
        lqw.eq(StringUtils.isNotBlank(bo.getIdcardType()), TalentDeclarationInfo::getIdcardType, bo.getIdcardType());
        lqw.eq(StringUtils.isNotBlank(bo.getIdcardNum()), TalentDeclarationInfo::getIdcardNum, bo.getIdcardNum());
        lqw.eq(StringUtils.isNotBlank(bo.getSex()), TalentDeclarationInfo::getSex, bo.getSex());
        lqw.eq(bo.getBirthday() != null, TalentDeclarationInfo::getBirthday, bo.getBirthday());
        lqw.eq(StringUtils.isNotBlank(bo.getPhonenumber()), TalentDeclarationInfo::getPhonenumber, bo.getPhonenumber());
        lqw.like(StringUtils.isNotBlank(bo.getWorkCompanyName()), TalentDeclarationInfo::getWorkCompanyName, bo.getWorkCompanyName());
        lqw.eq(StringUtils.isNotBlank(bo.getWorkCompanyType()), TalentDeclarationInfo::getWorkCompanyType, bo.getWorkCompanyType());
        lqw.eq(StringUtils.isNotBlank(bo.getQuxian()), TalentDeclarationInfo::getQuxian, bo.getQuxian());
        lqw.eq(StringUtils.isNotBlank(bo.getXiangzhen()), TalentDeclarationInfo::getXiangzhen, bo.getXiangzhen());
        lqw.eq(StringUtils.isNotBlank(bo.getGraduateFrom()), TalentDeclarationInfo::getGraduateFrom, bo.getGraduateFrom());
        lqw.eq(StringUtils.isNotBlank(bo.getMajor()), TalentDeclarationInfo::getMajor, bo.getMajor());
        lqw.eq(bo.getGraduateDate() != null, TalentDeclarationInfo::getGraduateDate, bo.getGraduateDate());
        lqw.eq(StringUtils.isNotBlank(bo.getLearningForms()), TalentDeclarationInfo::getLearningForms, bo.getLearningForms());
        lqw.eq(StringUtils.isNotBlank(bo.getDegree()), TalentDeclarationInfo::getDegree, bo.getDegree());
        lqw.eq(StringUtils.isNotBlank(bo.getNewFengjieTalentLevel()), TalentDeclarationInfo::getNewFengjieTalentLevel, bo.getNewFengjieTalentLevel());
        lqw.eq(StringUtils.isNotBlank(bo.getMeetChongqingTalentDesc()), TalentDeclarationInfo::getMeetChongqingTalentDesc, bo.getMeetChongqingTalentDesc());
        lqw.eq(StringUtils.isNotBlank(bo.getMeetFengjieTalentDesc()), TalentDeclarationInfo::getMeetFengjieTalentDesc, bo.getMeetFengjieTalentDesc());
        lqw.eq(StringUtils.isNotBlank(bo.getProvePapers()), TalentDeclarationInfo::getProvePapers, bo.getProvePapers());
        lqw.like(StringUtils.isNotBlank(bo.getTalentPaperName()), TalentDeclarationInfo::getTalentPaperName, bo.getTalentPaperName());
        lqw.eq(bo.getTalentPaperDate() != null, TalentDeclarationInfo::getTalentPaperDate, bo.getTalentPaperDate());
        lqw.eq(StringUtils.isNotBlank(bo.getProfessionalSkillLevel()), TalentDeclarationInfo::getProfessionalSkillLevel, bo.getProfessionalSkillLevel());
        lqw.eq(StringUtils.isNotBlank(bo.getSkillTalentType()), TalentDeclarationInfo::getSkillTalentType, bo.getSkillTalentType());
        lqw.eq(StringUtils.isNotBlank(bo.getHangyeType()), TalentDeclarationInfo::getHangyeType, bo.getHangyeType());
        lqw.eq(StringUtils.isNotBlank(bo.getIndustryCategory()), TalentDeclarationInfo::getIndustryCategory, bo.getIndustryCategory());
        lqw.eq(StringUtils.isNotBlank(bo.getJobCategory()), TalentDeclarationInfo::getJobCategory, bo.getJobCategory());
        lqw.like(StringUtils.isNotBlank(bo.getWorkLiaisonName()), TalentDeclarationInfo::getWorkLiaisonName, bo.getWorkLiaisonName());
        lqw.eq(StringUtils.isNotBlank(bo.getWorkLiaisonPhone()), TalentDeclarationInfo::getWorkLiaisonPhone, bo.getWorkLiaisonPhone());
        lqw.like(StringUtils.isNotBlank(bo.getServiceLiaisonName()), TalentDeclarationInfo::getServiceLiaisonName, bo.getServiceLiaisonName());
        lqw.eq(StringUtils.isNotBlank(bo.getServiceLiaisonPhone()), TalentDeclarationInfo::getServiceLiaisonPhone, bo.getServiceLiaisonPhone());
        lqw.like(StringUtils.isNotBlank(bo.getManageWorkName()), TalentDeclarationInfo::getManageWorkName, bo.getManageWorkName());
        lqw.eq(bo.getManageWorkId() != null, TalentDeclarationInfo::getManageWorkId, bo.getManageWorkId());
        lqw.like(StringUtils.isNotBlank(bo.getSubmitWorkName()), TalentDeclarationInfo::getSubmitWorkName, bo.getSubmitWorkName());
        lqw.eq(bo.getSubmitWorkId() != null, TalentDeclarationInfo::getSubmitWorkId, bo.getSubmitWorkId());
        lqw.eq(StringUtils.isNotBlank(bo.getAccreditationCriteria()), TalentDeclarationInfo::getAccreditationCriteria, bo.getAccreditationCriteria());
        lqw.eq(bo.getExpireDate() != null, TalentDeclarationInfo::getExpireDate, bo.getExpireDate());
        lqw.eq(StringUtils.isNotBlank(bo.getDeclarationFlag()), TalentDeclarationInfo::getDeclarationFlag, bo.getDeclarationFlag());
        lqw.eq(StringUtils.isNotBlank(bo.getDeclarationRemark()), TalentDeclarationInfo::getDeclarationRemark, bo.getDeclarationRemark());
        return lqw;
    }

    /**
     * 新增人才申报信息
     *
     * @param bo 人才申报信息
     * @return 是否新增成功
     */
    @Override
    public Boolean insertByBo(TalentDeclarationInfoBo bo) {
        TalentDeclarationInfo add = MapstructUtils.convert(bo, TalentDeclarationInfo.class);
        validEntityBeforeSave(add);
        boolean flag = talentDeclarationInfoMapper.insert(add) > 0;
        if (flag) {
            bo.setInfoId(add.getInfoId());
        }
        return flag;
    }

    /**
     * 修改人才申报信息
     *
     * @param bo 人才申报信息
     * @return 是否修改成功
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean updateByBo(TalentDeclarationInfoBo bo) {
        TalentDeclarationInfo needUpdate = MapstructUtils.convert(bo, TalentDeclarationInfo.class);
        validEntityBeforeAudit(needUpdate);
        boolean isPassed = "2".equals(needUpdate.getDeclarationFlag());
        if (isPassed) {
            needUpdate.setApproveTime(now());
            TalentUser talentUser = MapstructUtils.convert(needUpdate, TalentUser.class);
            talentUserMapper.insert(talentUser);
        }
        return talentDeclarationInfoMapper.updateById(needUpdate) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(TalentDeclarationInfo entity) {
        //TODO 做一些数据校验,如唯一约束
    }

    private void validEntityBeforeAudit(TalentDeclarationInfo entity) {
        Long infoId = entity.getInfoId();
        TalentDeclarationInfo talentDeclarationInfo = talentDeclarationInfoMapper.selectById(infoId);
        if ((talentDeclarationInfo.getAllotFlag() == null || talentDeclarationInfo.getAllotFlag().equals("0")) && entity.getManageWorkId() == null) {
            throw new ServiceException("请先完成主管部门分配");
        }
    }

    /**
     * 校验并批量删除人才申报信息信息
     *
     * @param ids     待删除的主键集合
     * @param isValid 是否进行有效性校验
     * @return 是否删除成功
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if (isValid) {
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return talentDeclarationInfoMapper.deleteByIds(ids) > 0;
    }

    @Override
    public List<TalentDeclarationInfoVo> getDeclarationList(Long userId) {
        LambdaQueryWrapper<TalentDeclarationInfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(TalentDeclarationInfo::getXcxUserId, userId);
        return talentDeclarationInfoMapper.selectVoList(queryWrapper);
    }

    @Override
    public Boolean submitDeclarationInfo(TalentDeclarationInfoBo talentDeclarationInfoBo, Long userId) {
        TalentDeclarationInfo add = MapstructUtils.convert(talentDeclarationInfoBo, TalentDeclarationInfo.class);
        add.setSuggestManageWorkId(add.getManageWorkId());
        add.setManageWorkId(null);
        add.setXcxUserId(userId);
        validEntityBeforeSave(add);
        boolean flag = talentDeclarationInfoMapper.insert(add) > 0;
        if (flag) {
            talentDeclarationInfoBo.setInfoId(add.getInfoId());
        }
        return flag;
    }

    @Override
    public TalentDeclarationInfoVo getDeclarationByInfoIdAndUserId(Long infoId, Long userId) {
        LambdaQueryWrapper<TalentDeclarationInfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(TalentDeclarationInfo::getXcxUserId, userId);
        queryWrapper.eq(TalentDeclarationInfo::getInfoId, infoId);
        return talentDeclarationInfoMapper.selectVoOne(queryWrapper);
    }

    @Override
    public Boolean submitDeclarationInfoUpdate(TalentDeclarationInfoBo bo) {
        TalentDeclarationInfo update = MapstructUtils.convert(bo, TalentDeclarationInfo.class);
        update.setSuggestManageWorkId(update.getManageWorkId());
        update.setManageWorkId(null);
        validEntityBeforeSave(update);
        //设置为待审核
        update.setDeclarationFlag("0");
        return talentDeclarationInfoMapper.updateById(update) > 0;
    }

    @Override
    public Boolean assignDept(TalentDeclarationInfoBo bo) {
        Long infoId = bo.getInfoId();
        TalentDeclarationInfo talentDeclarationInfo = talentDeclarationInfoMapper.selectById(infoId);
        talentDeclarationInfo.setManageWorkId(bo.getManageWorkId());
        talentDeclarationInfo.setAllotFlag("1");
        return talentDeclarationInfoMapper.updateById(talentDeclarationInfo) > 0;
    }

    @Override
    public List<SysDeptVo> optionDepts() {
        return sysDeptMapper.selectAllDeptList(new LambdaQueryWrapper<SysDept>()
            .select(SysDept::getDeptId, SysDept::getDeptName, SysDept::getLeader)
            .eq(SysDept::getStatus, SystemConstants.NORMAL));
    }

    @Override
    public Boolean returnDept(TalentDeclarationInfoBo bo) {
        Long infoId = bo.getInfoId();
        TalentDeclarationInfo talentDeclarationInfo = talentDeclarationInfoMapper.selectById(infoId);
        talentDeclarationInfo.setManageWorkId(null);
        talentDeclarationInfo.setAllotFlag("0");
        return talentDeclarationInfoMapper.updateById(talentDeclarationInfo) > 0;
    }
}
